#include "types.h"
#include "user.h"



void print_pid(int cid){
	int i;
	for(i = 1; i <= 500; i++){
		printf(1, " %d\n", cid);
	}
}

int
main(void)
{

	struct {
		int pid;
		int wtime;
		int rtime;
		int tatime;
	}children[30];

	int i,j;
	int pid;

	int wtime;//parameter to pass to wait2
	int rtime;//parameter to pass to wait2

	int total_wtime = 0;
	int total_rtime = 0;
	int total_tatime = 0;

//parent forks 30 children. An even numbered child calls nice and prints it's cid and exits
//An odd numbered child just prints it's cid and exits
	for(i = 0; i < 30; i++){
		children[i].pid = fork();
		if(children[i].pid == 0 && ((i % 2) == 0)){//an even numbered child
			nice();
			print_pid(i);
			exit();
		}
		else if(children[i].pid == 0 && ((i % 2) == 1)){//an odd numbered child
			print_pid(i);
			exit();
		}
	}

//the parent iterates and waits for it's children
//summing up the total waiting time and total running time
//each child saves it's statistics to be printed later on
	for(i = 0; i < 30; i++){
		pid = wait2(&wtime, &rtime);

		for (j = 0; j < 30; j++){
		  if (children[j].pid == pid) {
			children[j].wtime = wtime;
			children[j].rtime = rtime;
			children[j].tatime = wtime + rtime;
			break;
		  }
		}
		total_wtime += wtime;
		total_rtime += rtime;
	}

//parent calculates total turnaround time
//and prints the average statistics
		total_tatime = total_wtime + total_rtime;
		printf(1, "Average waiting time: %d\n", total_wtime / 30);
		printf(1, "Average running time: %d\n", total_rtime / 30);
		printf(1, "Average turnaround time: %d\n", total_tatime / 30);

//parent iterates and prints each child's statistics
//and exits when done
		for(i = 0; i < 30; i++){
			printf(1, "child: %d", i);
			//printf(1, " priority: %d", children[i].priority);
			printf(1, " pid: %d", children[i].pid);
			printf(1, " waiting time: %d", children[i].wtime);
			printf(1, " running time: %d", children[i].rtime);
			printf(1, " turnaround time: %d\n", children[i].tatime);
		}
	 exit();
}
